package jhh.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jhh.entity.JmxInfo;
import jhh.entity.ValidataInfo;
import jhh.service.JmxReader;
import jhh.service.MyValidataXML;


@WebServlet("/ValidataXML")
public class ValidataXML extends HttpServlet {

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter pw=response.getWriter();
		String path=this.getServletContext().getRealPath("upload");
		File f=new File(path);
		String[] paths=f.list();
		List<ValidataInfo> InfoList=new ArrayList<ValidataInfo>();
		String Xsdpath=this.getServletContext().getRealPath("WEB-INF/ValidataXml/MyXml.xml");
		for(int i=0;i<paths.length;i++){
			MyValidataXML validataXml=new MyValidataXML();
			JmxReader reader=new JmxReader();
			ValidataInfo info=validataXml.VaildataXML((path+File.separator+paths[i]),Xsdpath );
			String JmxPath=(path+File.separator+paths[i]);
			if(info.isResult()==true){
				//System.out.println(JmxPath);
				JmxInfo Jinfo=reader.ReaderJmx(JmxPath);
				info.setJmxInfo(Jinfo);
			}
			info.setJmxName(paths[i]);
			InfoList.add(info);
		}
		String json = Test.JSON.Encode(InfoList);
		pw.write(json);
	    pw.close();
	   
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
